import axios from "axios";
import apiconfig from "./apiConfig";
import router from '@/view/teamActivity/router/route.js'
import qs from 'qs'
import Vue from 'vue'
// import mockData from "./mockData"
const codeArray = [-1, 5004, 5005]; //登陆失效返回的code码
function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  arr = document.cookie.match(reg)
  if (arr) {
    return unescape(arr[2]);
  } else {
    return null;
  }
}
const commonAxios = axios.create();
commonAxios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
// commonAxios.defaults.withCredentials = true;
// commonAxios.defaults.timeout = 5000;   
const payAxios = (option) => {
  commonAxios.defaults.baseURL = apiconfig['API'][option.baseUrl];
  commonAxios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  if (option.contentType) {
    commonAxios.defaults.headers.common['content-Type'] = option.contentType;
  }
  return commonAxios;
};

let hostLocal = apiconfig.YX_WEB;
let ssoapihost = apiconfig.SSO_API_HOST;
export const getKeyHref = function (key) {
  let href = window.location.href;
  let arraykey = [];
  if (href.indexOf("?") > -1) {
    arraykey = href.split("?")[1].split("&");
  } else {
    return;
  }
  let obj = {};
  for (let i = 0; i < arraykey.length; i++) {
    let item = arraykey[i].split("=");
    obj[item[0].toUpperCase()] = item[1];
  }
  return obj[key]
}
export const isLogin = async function () {
  let returnUrl=''
  if(window.location.href.indexOf("teamActivity")){
    returnUrl=apiconfig['returnURLTeam']+router.currentRoute.params.activityCode;
  }else{
    returnUrl=apiconfig['returnURL'];
  }
  let newHref=apiconfig["YX_WEB"]+'/search/common/login?returnUrl='+returnUrl+'?appId='+apiconfig['appid'];
  window.location.href=newHref;
}
commonAxios.interceptors.request.use(function (config) {
  
  //添加token

  if (window.location.origin.indexOf("localhost") >= 0) {
    config.headers.common['accesstoken'] = apiconfig['DEV_Token'];
  } else {
    if (!getCookie(apiconfig['enveriment']) || getCookie(apiconfig['enveriment']) == null) {
      let lid = qs.parse(window.location.href.split("?")[1])
      let calLID = lid[apiconfig['enveriment']] || lid[apiconfig['enveriment'].toLowerCase()];
      if (calLID) {
        Vue.$cookies.set(apiconfig['enveriment'], decodeURIComponent(calLID), 60 * 60 * 24, '/', '.cnki.net');
        // Vue.$cookies.set(apiconfig['enveriment'], decodeURIComponent(calLID), 60 * 60 * 24, '/', '192.168.50.179');
      } else {
        isLogin();
      }
    }
    config.headers.common['accesstoken'] = getCookie(apiconfig['enveriment']);

  }
  return config;
}, function (error) {
  return Promise.reject(error);
});




// 添加响应拦截器
commonAxios.interceptors.response.use(function (response) {
  if (response.status == 200) {
    if (response.data.errcode == 401 || response.data.Code == -1 || response.data.errcode == -1 || response.data.Code == 5004 || response.data.Code == 5005) {
      isLogin();
    } else {
      if (apiconfig.IS_MOCK) {
        //使用mock数据   
        let arr = response.config.url.split("/");
        let mocked = mockData[arr[arr.length - 1]]._mocked;
        response.data = tolower(mocked[`/${arr[arr.length-1]}${response.config.method}`].template());
      } else {
        response.data = tolower(response.data);
      }
      return response.data;
    }
  } else {
    switch (response.status) {
      case 400:
        console.log('错误请求')
        break
      case 401:
        console.log('未授权，请重新登录')
        isLogin()
        break
      case 403:
        console.log('拒绝访问')
        break
      case 404:
        console.log('请求错误,未找到该资源')
        break
      case 405:
        console.log('请求方法未允许')
        break
      case 408:
        console.log('请求超时')
        break
      case 500:
        console.log('服务器端出错')
        break
      case 501:
        console.log('网络未实现')
        break
      case 502:
        console.log('网络错误')
        break
      case 503:
        console.log('服务不可用')
        break
      case 504:
        console.log('网络超时')
        break
      case 505:
        console.log('http版本不支持该请求')
        break
      default:
        console.log(`连接错误${response.status}`)
    }
  }
}, function (error) {
  if (error.response&&error.response.status == 401) {
    isLogin();
  }
  return Promise.reject(error);
});

function tolower(obj) {
  // 将所有返回的key转为小写
  for (let item in obj) {
    obj[item.toLocaleLowerCase()] = obj[item];
    if (Object.prototype.toString.call(obj[item]) == "[object Array]" || Object.prototype.toString.call(obj[item]) == "[object Object]") {
      obj[item] = tolower(obj[item]);
    }
  }
  return obj;
}


export default payAxios;